package controllers

import (
	"github.com/astaxie/beego"
	"servermg/log"
	"servermg/models"
	"strconv"
)

type SmanagerController struct {
	beego.Controller
}

func (this *SmanagerController) AddType() {

	name := this.Input().Get("name")
	desc := this.Input().Get("desc")
	if len(name) == 0 || len(desc) == 0 {
		this.TplName = "stype_add.html"
		return
	}

	var opts []int
	for _, opt := range models.Opts {
		key := "opt" + strconv.Itoa(opt)
		val := this.Input().Get(key)

		if val == "on" {
			opts = append(opts, opt)
		}
	}
	log.Debug("opts :", opts)

	err := models.AddSType(name, desc, opts)
	if err != nil {
		log.Error(err.Error())
	}
	this.Redirect("/smanager", 301)

}

func (this *SmanagerController) DelType() {
	id := this.Input().Get("id")
	log.Debug("del type id", id)

	defer this.Redirect("/smanager", 301)

	if len(id) == 0 {
		log.Error("id is NULL")
	}

	err := models.DelSType(id)
	if err != nil {
		log.Error(err.Error())
	}

}

func (this *SmanagerController) AddServer() {
	this.TplName = "server_add.html"
	stype := this.Input().Get("stype")
	this.Data["Stype"] = stype

	svid := this.Input().Get("svid")
	var err error
	if len(svid) > 0 {
		name := this.Input().Get("name")
		addr := this.Input().Get("addr")
		port := this.Input().Get("port")
		err = models.AddServer(svid, stype, name, addr, port)
	}

	this.Data["Servers"], err = models.GetStypeServer(stype)
	if err != nil {
		log.Error(err.Error())
	}
}

func (this *SmanagerController) Get() {

	this.TplName = "smanager.html"
	this.Data["IsSmanager"] = true
	var err error
	this.Data["STypes"], err = models.GetAllSTypes()
	if err != nil {
		beego.Error(err)
	}
}
